// miniprogram/pages/my/index.js
const {
  wxLogin,
  wxMobileLogin,
  decodeUserInfo,
  sysSetting
} = require('../../api/login')
const {
  getScore,
  payMember,
  getDictData,
  mainViewPic
} = require('../../api/api')
const config = require('../../config/config')
const {
  checkLogin,
  canParseToJson
} = require('../../utils/util')
var timer = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navHeight: getApp().globalData.navHeight,
    navTop: getApp().globalData.navTop,
    menuHeight: getApp().globalData.menuHeight,
    isLogin: false,
    userInfo: {},
    isVip: false,
    picList: [
      'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/user/banner.jpg',
    ],
    navList: [{
        child: [{
            name: '个人信息',
            icon: '/images/my/my_icon1.png',
            url: '/pages/users/index/index'
          },
          {
            name: '我的评测',
            icon: '/images/my/my_icon2.png',
            url: '/pages/users/test/index'
          },
          {
            name: '我的选科',
            icon: '/images/my/my_icon12.png',
            url: '/pages/optional/my/index'
          },

        ]
      },
      {
        child: [{
            name: '收藏的院校',
            icon: '/images/my/my_icon3.png',
            url: '/pages/users/collect/index'
          }, {
            name: '收藏的专业',
            icon: '/images/my/my_icon4.png',
            url: '/pages/users/specialty/index'
          },
          {
            name: '收藏的课程',
            icon: '/images/my/my_icon11.png',
            url: '/pages/users/course/index'
          },
        ]
      },
      {
        child: [{
            name: '许愿墙',
            icon: '/images/my/my_icon5.png',
            url: '/pages/users/wish/new/index',
            type: '1'
          },
          // {
          //   name: '产品服务',
          //   icon: '/images/my/my_icon6.png',
          //   url: '/pages/users/invite/index'
          // }, {
          //   name: '使用教程',
          //   icon: '/images/my/my_icon7.png',
          //   url: ''
          // },
        ]
      },
      {
        child: [{
          auth:false,
          name: '问题反馈',
          icon: '/images/my/my_icon8.png',
          url: '/pages/users/feedback/index'
        }, {
          auth:false,
          name: '隐私政策',
          icon: '/images/my/my_icon9.png',
          url: '/pages/users/secret/index'
        }, {
          auth:false,
          name: '关于我们',
          icon: '/images/my/my_icon10.png',
          url: '/pages/users/about/index'
        }]
      },
    ],
    phoneNumber: '',
    total: 168412,
    arrayIndex: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    maxTotal: 201020,
    currentRegion: {},
    tabbarHeight: getApp().globalData.tabbarHeight,
    vipType: '',
    allCount: 0,
    picBanner3: 'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/my/share_banner.png'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    getApp().getMessageNum().then(allCount => {
      this.setData({
        allCount
      })
    })
    let self = this;
    getApp().watch({
      allCount(val) {
        self.setData({
          allCount: val
        })
      }
    })
    wx.hideTabBar()
    getApp().editTabbar()
    this.getPicList()
  },

  calculatorUser() {
    var {
      total,
      maxTotal
    } = this.data
    var _this = this
    timer = setInterval(function () {
      if (total >= maxTotal) {
        clearInterval(timer)
        return
      }
      total = total + 1
      const totalStr = total.toString()
      const array = totalStr.split('')
      const totalArray = array.map((item) => {
        return parseInt(item)
      })
      _this.setData({
        total,
        totalArray
      })
      wx.setStorageSync('total', total)
    }, 5000)
  },
  onHide() {
    clearInterval(timer)
  },
  catchTouchMove(e) {
    return false
  },
  logout() {
    var that = this;
    wx.showLoading({
      title: '正在退出',
    })
    const filterList = [
      "total","token", "ids", "userCitys", "userInfo", "chooseList", "mainSubject", "ranking", "score", "year", "subjectInfo", "mobile", "loginTime","scanChar","promoteUser"
    ]
    filterList.map((item) => {
      wx.removeStorageSync(item)
    })
    setTimeout(() => {
      wx.hideLoading()
      wx.switchTab({
        url: '/pages/index/index',
      })
      that.setData({
        isVip: false,
      })
    }, 1000);
  },
  onShow: function () {
    this.getUserTotal()
    let that = this
    const {
      token
    } = this.data
    checkLogin().then(async (res) => {
      this.setData({
        isLogin: true,
        // allCount,
      })
      this.fetchUserInfo()
      if (token === wx.getStorageSync('token')) {
        return
      }
      this.setData({
        token: wx.getStorageSync('token')
      })
      this.getScore()
    }).catch((e) => {
      this.setData({
        isLogin: false
      })
    })

  },
  async getUserTotal() {
    const result = await getApp().fetchUserTotal()
    var total = wx.getStorageSync('total') || (result.yesterday + 168412)
    var maxTotal = (result.today + 168412)
    const totalStr = total.toString()
    const array = totalStr.split('')
    const totalArray = array.map((item) => {
      return parseInt(item)
    })
    this.setData({
      currentRegion: wx.getStorageSync('userCitys'),
      total: total,
      totalArray,
      maxTotal
    })
    this.calculatorUser()
  },
  goto(e) {
    const url = e.currentTarget.dataset.url
    const auth = e.currentTarget.dataset.auth
    if(auth===false){
      wx.navigateTo({
        url: url,
      })
      return
    }
    checkLogin().then((res) => {
      wx.navigateTo({
        url: url,
      })
    }).catch((e) => {
      this.setData({
        isLogin: false
      })
      // wx.showToast({
      //   title: '请先登录！',
      //   icon: 'none',
      //   duration:1500
      // })
       wx.navigateTo({url:"/pages/login/index"})
    })


  },

  async getConfig() {
    const {
      result
    } = await sysSetting()
    this.setData({
      phoneNumber: result[0].mobile
    })
  },
  async getPicList() {
    // let {
    //   result
    // } = await getDictData('user_swiper')
    const param = {
      status: 1,
      type:3
    }
    let {
      result
    } = await mainViewPic(param)
    result = result.map((item) => {
      let isStringToJson = canParseToJson(item.redirectUrl)
      return Object.assign(item, isStringToJson ? JSON.parse(item.redirectUrl) : {
        url: item.redirectUrl
      })
    })
    this.setData({
      picList: result
    })
  },
  async fetchUserInfo() {
    const userInfo = await getApp().fetchUserInfo()
    this.setData({
      userInfo,
      vipType: userInfo.vipType
    })
    if (userInfo.mobile == '') {
      return
    }
    wx.setStorageSync(config.storageKey.mobile, userInfo.mobile)
  },
  getUserProfile(e) {
    var that = this
    let newTime = Math.round(new Date())
    wx.showLoading({
      title: '登陆中',
    })
    wx.setStorageSync(config.storageKey.loginTime, newTime);
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: async function (res) {
        // console.log(res)
        const {
          encryptedData,
          iv,
        } = res;
        const info = res.userInfo
        wx.login({
          success: async function (ress) {
            const param = {
              avatarUrl: info.avatarUrl,
              city: info.city,
              code: ress.code,
              country: info.city,
              encryptedData,
              iv,
              language: info.language,
              merchantId: 0,
              nickName: info.nickName,
              promoterId: 0,
              province: info.province,
              sex: info.gender,
              promoteUser: wx.getStorageSync('promoteUser'),
            }
            // console.log(param)
            wx.hideLoading()
            const {
              result
            } = await wxLogin(param);
            const {
              userInfo,
              token,
            } = result
            wx.setStorageSync(config.storageKey.token, token)
            that.fetchUserInfo()
            that.getScore()
            that.setData({
              userInfo,
              isLogin: true,
              isVip: (userInfo.isVip && userInfo.isVip) > 0,
            })
          }
        })

      },
      fail: function (res) {
        wx.hideLoading()
      }
    })

  },
  login() {
    wx.navigateTo({
      url: '/pages/login/index',
    })
  },
  onLoadFunc() {
    // this.getScore()
  },
  async getScore() {
    let spreadUserId = wx.getStorageSync('spreadUserId')
    var {
      result
    } = await getScore(spreadUserId)
    if (result && result.provinceId && result.secondSelect) { //新用户无成绩时
      this.setData({
        ...result
      })
      const subjectList = wx.getStorageSync('subjectList') || await getApp().getSubjectList()
      const cityList = wx.getStorageSync('cityList') || await getApp().getCityList()
      const currentCityList = cityList.filter((item) => {
        return item.id == result.provinceId
      })
      let newTime = Math.round(new Date())
      const userCitys = {
        code: currentCityList[0].id,
        name: currentCityList[0].title,
        time: newTime
      }
      let checkedIds = []
      const secondSelect = result.secondSelect == '' ? [] : result.secondSelect.split(',')
      var firstSelectSubjects = ''
      var secondSelectSubjects = []
      subjectList.map((item) => {
        if (result.firstSelect !== '' && item.id == result.firstSelect) {
          firstSelectSubjects = item.name
          checkedIds.push(parseInt(result.firstSelect))
        }
        if (secondSelect.indexOf(item.id) > -1 || secondSelect.indexOf(item.id.toString()) > -1) {
          secondSelectSubjects.push(item.name)
          checkedIds.push(parseInt(item.id))
        }
      })
      result.firstSelectSubjects = firstSelectSubjects
      result.secondSelectSubjects = secondSelectSubjects.join(',')
      if (checkedIds.length > 0) {
        wx.setStorageSync('ids', checkedIds)
      }
      wx.setStorageSync('mainSubject', result.firstSelect == '' ? '' : parseInt(result.firstSelect))
      wx.setStorageSync('score', result.score)
      wx.setStorageSync('ranking', result.ranking)
      wx.setStorageSync('year', result.year)
      wx.setStorageSync('userCitys', userCitys)
      wx.setStorageSync('subjectInfo', result)
      this.setData({
        currentRegion: userCitys
      })
    } else {
      // this.setData({
      //   showModal: true
      // })
    }

  },
  async getPhoneNumber(e) {
    const {
      encryptedData,
      iv
    } = e.detail
    wx.login({
      success: async function (res) {
        var code = res.code
        const param = {
          code,
          encryptedData,
          iv
        }
        const data = await wxMobileLogin(param)
      }
    })
  },
  onShareAppMessage() {
    return {
      title: '德道升学',
      path: '/pages/my/index?scene=' + wx.getStorageSync('userInfo').id,
      imageUrl: 'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/shareImg.jpg'
    }
  }

})
